package com.bd.rj.frontstage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bd.rj.common.entity.Post;
import com.bd.rj.frontstage.mapper.PostMapper;
import com.bd.rj.frontstage.service.IPostService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 白世俊
 * @since 2025-01-03
 */
@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements IPostService {

    private final PostMapper postMapper;

    /**
     * @param postMapper
     * @author WBW
     * @desc 获取最新岗位
     */
    @Autowired
    public PostServiceImpl(PostMapper postMapper) {
        this.postMapper = postMapper;
    }


//    @Override
//    public List<Post> conditionSelectPost(String address, String type, String salary) {
//        return postMapper.conditionSelectPost(address,type,salary);
//    }

    /**
     * @param address 地区
     * @param type    类型
     * @param salary  薪资
     * @param page    分页
     * @return
     * @author WBW
     * @desc 条件筛选岗位
     */
    @Override
    public IPage<Post> conditionSelectPost(String address, String type, String salary, Page<Post> page) {
        return baseMapper.selectPage(page, new LambdaQueryWrapper<Post>()
                .eq(address != null && !address.isEmpty(), Post::getAddress, address)
                .eq(type != null && !type.isEmpty(), Post::getType, type)
                .eq(salary != null && !salary.isEmpty(), Post::getSalary, salary));
    }

    /**
     * @return
     * @author WBW
     * @desc 获取热门岗位
     */
    @Override
    public List<Post> getHotPost() {
        return postMapper.gethotPost();
    }

    /**
     * @param postname 岗位名称
     * @param uid      用户id
     * @return
     * @throws JsonProcessingException
     * @author WBW
     * @desc 调用python接口发送用户搜索记录
     */
    @Override
    public String postPython(String postname, Long uid) throws JsonProcessingException {
        // 创建 RestTemplate 实例
        RestTemplate restTemplate = new RestTemplate();
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> requestData = new HashMap<>();
        requestData.put("uid", uid);
        requestData.put("postname", postname);
        // 将 Map 转换为 JSON 字符串
        String jsonData = objectMapper.writeValueAsString(requestData);
        // 创建 HTTP 请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 创建 HTTP 请求实体
        HttpEntity<String> request = new HttpEntity<>(jsonData, headers);
        // 发送 POST 请求
        String url = "http://26.204.166.92:5000/recordsearch";

        // 返回路径
        return restTemplate.postForObject(url, request, String.class);

    }

    /**
     * @param uid 用户id
     * @return
     * @author WBW
     * @desc 获取推荐岗位信息
     */

    public List<Post> getPostByUid(Long uid) {
//        String url = "http://10.2.1.8:5000/jobcommend";

        StringBuilder urlBuilder = new StringBuilder("http://26.204.166.92:5000/jobcommend");
        urlBuilder.append("?uid=").append(uid);
        String url = urlBuilder.toString();

        RestTemplate restTemplate = new RestTemplate();

        // 发送GET请求并获取响应
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        // 判断响应状态码是否为200 OK
        if (response.getStatusCode().is2xxSuccessful()) {
            HttpHeaders headers = response.getHeaders();
            List<MediaType> mediaTypes = headers.getAccept();
            Charset charset = StandardCharsets.UTF_8;
            if (mediaTypes != null && !mediaTypes.isEmpty()) {
                MediaType mediaType = mediaTypes.get(0);
                if (mediaType.getCharset() != null) {
                    charset = mediaType.getCharset();
                }
            }
            String responseBody = new String(response.getBody().getBytes(StandardCharsets.ISO_8859_1), charset);

            try {
                ObjectMapper objectMapper = new ObjectMapper();
                // 假设返回的是JSON数组，直接转换为List<Post>
                List<Post> posts = objectMapper.readValue(responseBody,
                        objectMapper.getTypeFactory().constructCollectionType(List.class, Post.class));
                return posts;
            } catch (Exception e) {
                e.printStackTrace();
                return new ArrayList<>();
            }
        } else {
            System.out.println("Error: " + response.getStatusCode());
            return new ArrayList<>();
        }

    }


}
